package com.littlebee.storychild.ui;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.littlebee.storychild.R;
import com.littlebee.storychild.common.utils.DateUtils;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.widget.CustomVideoView;
import com.littlebee.storychild.ui.entry.Cartoons;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.widget.CommonProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/***
 * 英语详情页
 *
 */
public class EnglishInfoActivity extends AppCompatActivity implements View.OnClickListener {

    Cartoons entrys;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    //获取日期格式器对象
    Calendar calendar = Calendar.getInstance(Locale.CHINA);
    String dateStr = "";

    /**
     * 是否在播放
     */
    private boolean isPlaying;
    /**
     * 播放进度
     */
    private int currPost = 0;
    /**
     * 用于做延迟加载
     */
    private Handler handler = null;
    /**
     * 视频播放组件
     */
    private CustomVideoView videoView;
    /**
     * 播放or暂停
     */
    private ImageView playPauseIv;
    /**
     * 播放进度
     */
    private TextView nowProgressTv;
    /**
     * 播放进度条
     */
    private SeekBar progressBar;
    /**
     * 总进度
     */
    private TextView totalLengthTv;
    private int diversityIndex=0;

    /**
     * 播放以前的初始化图片
     */
    private ImageView videoInitIv;
    /**
     * 视频标题
     */
    private TextView videoTitleTv;


    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_english_info);
        initView();
    }

//    @Override
//    public int getLayoutResId() {
//        return R.layout.activity_english_info;
//    }

    //@Override
    public void initView() {
        //super.initView();
        entrys = (Cartoons) getIntent().getSerializableExtra("info");
        handler = new Handler();
        videoInitIv = (ImageView) findViewById(R.id.init_video_iv);
        videoTitleTv = (TextView) findViewById(R.id.video_title_tv);

        videoView = (CustomVideoView) findViewById(R.id.video_view);
        playPauseIv = (ImageView) findViewById(R.id.play_pause_iv);
        nowProgressTv = (TextView) findViewById(R.id.now_progress_tv);
        progressBar = (SeekBar) findViewById(R.id.progressBar);
        totalLengthTv = (TextView) findViewById(R.id.total_length_tv);
        playPauseIv.setOnClickListener(this);
        progressBar.setOnSeekBarChangeListener(change);
        playPauseIv.performClick();
        findViewById(R.id.back_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Glide.with(EnglishInfoActivity.this).load(entrys.getCartoonminiphoto()).error(R.color.module_video_bg).into(videoInitIv);


    }

   // @Override
    public void initData(Bundle savedInstanceState) {
        //super.initData(savedInstanceState);

    }



    private void initPlayer(int diversityIndex, int currPost) {
        videoInitIv.setVisibility(View.GONE);
        videoTitleTv.setVisibility(View.GONE);

        playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);

        videoTitleTv.setText(entrys.getCartoonname());
        play(entrys.getCartoonplayurl(), currPost);
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView != null && videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
                //修改时间
            }
        }
    };

    /**
     * 播放咯
     *
     * @param path 地址
     * @param msec 播放进度
     */
    protected void play(String path, int msec) throws NullPointerException {
        //获取视频文件地址

        videoView.setVideoURI(Uri.parse(path));
        LogUtils.i("XHX", "初始化播放器了");
        //开始播放
        videoView.start();

        // 按照初始位置播放
        videoView.seekTo(msec);

        //修改时间
        // 开始线程，更新进度条的刻度
        new Thread() {
            @Override
            public void run() {
                try {
                    isPlaying = true;
                    while (isPlaying) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition();
                        progressBar.setMax(videoView.getDuration());
                        progressBar.setProgress(current);
                        handler.post(runnableUi);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调 续播还是结束播放
//                if (diversityIndex < names.size() - 1) {
//                    diversityIndex += 1;
//                    currPost = 0;
//                    videoTitleTv.setText(names.get(diversityIndex).getCartoonname());
//                    play(names.get(diversityIndex).getCartoonplayurl(), currPost);
//                } else {
                    videoInitIv.setVisibility(View.VISIBLE);
                    videoTitleTv.setVisibility(View.VISIBLE);
                    ToastUtil.displayShortToast("播放结束");

               // }
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //TODO  发生错误重新播放
                play(entrys.getCartoonplayurl(), 0);
                isPlaying = false;
                return false;
            }
        });
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            if (videoView.getDuration() != -1) {
                totalLengthTv.setText(DateUtils.getTimeString(videoView.getDuration()));
            }
            nowProgressTv.setText(DateUtils.getTimeString(videoView.getCurrentPosition()));

        }

    };

//    @Override
//    public void setTopBar() {
//        super.setTopBar();
//        setStatusBarColor(R.color.module_video_bg);
//        CommonToolbar toolbar = getToolbar();
//        toolbar.setBgRes(R.color.module_video_bg);
//        toolbar.setTitle(entrys.getCartoonname());
//        toolbar.setVisibility(View.GONE);
//        getActivity().
//
//    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_pause_iv:
                if (videoView != null && videoView.isPlaying()) {
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                    currPost = videoView.getCurrentPosition();
                    videoView.pause();
                    isPlaying = false;

                } else {

                    playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);
                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            videoInitIv.setVisibility(View.GONE);
                            videoTitleTv.setVisibility(View.GONE);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.sendEmptyMessageDelayed(1, 0);
                                }
                            }).start();
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.sendEmptyMessageDelayed(0, 0);
                        }
                    }).start();
                    play(entrys.getCartoonplayurl(), currPost);

                }
                break;
        }
    }
    private static CommonProgressDialog dialog;

    public static void showProgressDialog(Context mContext, final String showStr) {
        if (mContext != null) {
            if (dialog == null) {
                dialog = new CommonProgressDialog(mContext);
                dialog.setTitle(showStr);
                dialog.setCancelable(true);
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
                        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                            dialog.dismiss();
                            dialog = null;
                        }
                        return false;
                    }
                });
                dialog.show();
            } else {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            }
        }
    }

    public static void dismissProgressDialog(Context mContext) {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    showProgressDialog(EnglishInfoActivity.this,"正在缓冲……");
                    break;
                case 1:
                    dismissProgressDialog(EnglishInfoActivity.this);
                    break;

            }
        }

    };
}
